
import time
import uvicorn
from fastapi import FastAPI

from models import aioDb
from utils.redis import aioRedis
from routers import create_router
from docs_tags import get_tags_metadata
from settings.log import logger, logger_handle


# 初始化API
app = FastAPI(
    version="0.0.1",
    title="new-pidan-for-fastapi",
    description="new-pidan-for-fastapi",
    openapi_tags=get_tags_metadata()
)

# 导入路由
create_router(app)


@app.on_event("startup")
async def startup():
    """
    APP启动配置
        1. 异步启动数据库连接池
        2. 异步启动Redis连接池
    """
    logger.info(f"********************  START:{time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))} ********************")
    logger.info("启动数据库连接池")
    await aioDb.connect_pool()
    logger.info("启动Redis连接池")
    await aioRedis.redis_connect_pool()
    logger.info("KEY写入文件")
    try:
        from dependencies import token
        with open("store/key.txt", "w", encoding="utf-8") as fw:
            fw.write(f"SECRET_KEY:{token.SECRET_KEY}\n")
            fw.write(f"ACCESS_TOKEN_KEYS:{token.ACCESS_TOKEN_KEYS}\n")
            fw.write(f"AES_KEY:{token.AES_KEY}\n")
            fw.write(f"AES_IV:{token.AES_IV}\n")
    except Exception as error:
        logger.error(f"KEY写入文件失败:{error}")


@app.on_event("shutdown")
async def shutdown():
    """
    APP停止运行时配置
        1. 异步关闭数据库连接池
        2. 异步关闭Redis连接池
    """
    try:
        logger.info("关闭数据库连接池")
        await aioDb.close()
    except Exception as error:
        logger.error(error)
    try:
        logger.info("关闭Redis连接池")
        await aioRedis.close()
    except Exception as error:
        logger.error(error)

    try:
        logger.info(f"*********  END:{time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))} *********")
        logger.remove(logger_handle)
    except:
        pass

if __name__ == '__main__':
    uvicorn.run('app:app', host='127.0.0.1', port=8088, debug=True, reload=True)
